package com.fashiontextile.user.controller;

import com.fashiontextile.user.entity.Image;
import com.fashiontextile.common.entity.R;
import com.fashiontextile.user.service.ImageService;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * @author brooke_zb
 */
@RestController
@AllArgsConstructor
@RequestMapping("/image")
public class ImageController {
    ImageService imageService;

    /**
     * 根据id获取图片链接
     * @param iid 图片id
     */
    @GetMapping("/id/{iid}")
    public R<?> getImageById(@PathVariable("iid") Long iid) {
        Image image = imageService.getImageById(iid);
        if (image == null) {
            return R.fail("获取图片失败");
        }
        return R.success(image);
    }

    /**
     * 根据pointTo获取图片链接
     * @param pointTo 图片指向id
     * @param diid 图片类型字典id
     */
    @GetMapping("/type/{diid}/pointto/{pointTo}")
    public R<?> getImageByPointTo(@PathVariable("pointTo") Long pointTo, @PathVariable("diid") Long diid) {
        List<Image> images = imageService.getImageByPointTo(diid, pointTo);
        if (images == null) {
            return R.fail("获取图片失败");
        }
        return R.success(images);
    }

    /**
     * 上传图片，获取图片链接
     * @param diid 图片类型字典id
     * @param picture 图片文件
     */
    @PostMapping("/type/{diid}")
    public R<?> uploadImage(@PathVariable("diid") Long diid, @RequestPart("picture") MultipartFile picture) {
        try {
            Image image = imageService.uploadImage(diid, picture);
            if (image == null) {
                return R.fail("上传失败");
            } else {
                return R.success(image);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail("上传失败");
        }
    }

    /**
     * 上传图片链接
     * @param images 图片列表
     */
    @PostMapping("")
    public R<?> uploadImage(@RequestBody List<Image> images) {
        if (imageService.uploadImageLink(images)) {
            return R.success(null, "上传成功");
        }
        return R.fail("上传失败");
    }

    /**
     * 根据指向id删除其所有图片链接
     * @param pointTo 图片指向id
     * @param diid 图片类型字典id
     */
    @DeleteMapping("/type/{diid}/pointto/{pointTo}")
    public R<?> deleteImageByPointTo(@PathVariable("pointTo") Long pointTo, @PathVariable("diid") Long diid) {
        if (imageService.deleteImageByPointTo(pointTo, diid)) {
            return R.success(null, "删除成功");
        }
        return R.fail("删除失败");
    }

    /**
     * 根据id删除图片链接
     * @param id 图片id
     */
    @DeleteMapping("/id/{id}")
    public R<?> deleteImageById(@PathVariable("id") Long id) {
        if (imageService.deleteImageById(id)) {
            return R.success(null, "删除成功");
        }
        return R.fail("删除失败");
    }
}
